package com.ycl.gatewayservice.filter;

import com.alibaba.nacos.common.utils.StringUtils;
import com.ycl.JwtUtils;
import com.ycl.RsaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenAuthorizationFilter implements GlobalFilter, Ordered {
    //白名单
    public static final String[] WHITE_LIST = {"/login","/register"};
    private static Logger logger =
            LoggerFactory.getLogger(TokenAuthorizationFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain
            chain) {
        //获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断请求url是否包含白名单，包含就直接放行
        for(String url : WHITE_LIST){
            if(request.getURI().toString().contains(url)){
                return chain.filter(exchange);
            }
        }
        //从请求头获得token
        String token = request.getHeaders().getFirst("Authorization");
        //判断token不是空的
        if(StringUtils.hasText(token)){
            try {
                //对token解析
                String username = JwtUtils.getUsernameFromToken(token,
                        RsaUtils.publicKey);
                logger.debug("token解析成功：{}", username);
                //如果能够成功，就放行请求
                return chain.filter(exchange);
            }catch (Exception ex){
                logger.error("token解析出现错误：{}",ex.getMessage());
                //返回客户错误信息
                response.setStatusCode(HttpStatus.OK);
                DataBuffer dataBuffer = response.bufferFactory().wrap("Token is wrong!".getBytes());
                return response.writeWith(Mono.just(dataBuffer));
            }
        }
        logger.error("token为空");
        //返回客户错误信息
        response.setStatusCode(HttpStatus.OK);
        DataBuffer dataBuffer = response.bufferFactory().wrap("Token is empty!".getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
